24. 两两交换链表中的节点

24. 两两交换链表中的节点

Similar Question

leading to the advanced question

Solution Tips

方案一: 迭代

dummyHead
dummyHead
1
1
2
2
3
3
Cur
Cur
Prev
Prev
Next
Next
X
X
1. cur.next.next = cur
1. cur.next.next = cur
2. prev.next = cur.next
2. prev.next = cur.ne...
3. cur.next = next
3. cur.next = next
X
X
X
X
Text is not SVG - cannot display

    swapPairs() {
        const dummyHead = new Node(0);
        dummyHead.next = this.head;

        let cur = this.head;
        let prev = dummyHead;

        while (cur !== null && cur.next !== null) {
            // cur 和 next 互换
            const next = cur.next.next;
            cur.next.next = cur;
            prev.next = cur.next;
            cur.next = next;

            prev = cur;
            cur = next;
        };

        this.head = dummyHead.next;
        return dummyHead.next;
    }

方案二: 递归

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode next = head.next;
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }
}